// API调用函数
console.log('index.js 文件已加载！');

// 配置常量
const API_CONFIG = {
    //测试环境
    // BASE_URL: 'http://47.108.207.134:8080/province/CrbtByProvice/ShanXi',
    //生产环境
    BASE_URL: 'https://ldwxmc.com/CrbtByProvice/ShanXi',
    CHANNEL_CODE: '96060767',
    CPID: 'test',
    FEE: '4000',
    DEFAULT_SMS_ID: '100868865189133007',
    SUCCESS_CODE: '1000',
    BUSINESS_NAME: '陕西移动40元80GB超值流量包',
    APPLICATION_NAME: '成都律动无限文化传播有限公司'
};

// 全局变量存储短信ID
let currentSecSmsSendId = null;

// 全局变量存储时间记录
let timeRecords = {
    clickUrlTime: Date.now(), // 页面加载时间
    printMobileTime: null,    // 输入手机号时间
    clickSmsBtnTime: null,    // 点击获取验证码时间
    clickHandleTime: null,    // 点击办理按钮时间
    clikcSecondHandleTime: null, // 二次确认时间
    responseSuccessTime: null,   // 响应成功时间
    getMemberTime: null          // 获取会员信息时间
};

// 倒计时相关全局变量
let smsTimer = null;
let smsTime = 59;

// 开始短信倒计时函数
function startSmsCountdown() {
    if (!smsTimer) {
        // 隐藏获取验证码文字，显示倒计时
        $('[onclick="API.sms_code();"] p').first().addClass('hide');
        $('.sms-wait').removeClass('hide');

        smsTimer = setInterval(() => {
            if (smsTime !== 0) {
                $(".sms-wait span").first().text(smsTime);
                smsTime--;
            } else {
                clearInterval(smsTimer);
                smsTimer = null;
                smsTime = 59;
                // 恢复按钮状态
                $('[onclick="API.sms_code();"] p').first().removeClass('hide');
                $('.sms-wait').addClass('hide');
                $('.sms-wait span').first().text('60');
            }
        }, 1000);
    }
}


// 1. 二次短信下发接口
function customSendTwiceSms(mobile) {
    // 记录点击获取验证码时间
    timeRecords.clickSmsBtnTime = Date.now();

    encryptMobile(mobile);

    const requestData = {
        mobile: mobile,
        cpid: API_CONFIG.CPID,
        fee: API_CONFIG.FEE,
        channelCode: API_CONFIG.CHANNEL_CODE
    };

    console.log('=== 二次短信下发接口 ===');
    console.log('请求URL:', `${API_CONFIG.BASE_URL}/twiceSmsSend`);
    console.log('请求参数:', requestData);

    return $.ajax({
        type: 'POST',
        url: `${API_CONFIG.BASE_URL}/twiceSmsSend`,
        contentType: 'application/json',
        data: JSON.stringify(requestData),
        success: function (response) {
            console.log('二次短信下发响应成功:', response);
            if (response.data?.returnCode === API_CONFIG.SUCCESS_CODE) {
                // 保存返回的secSmsSendId
                currentSecSmsSendId = response.data?.dataInfo;
                console.log('获取到secSmsSendId:', currentSecSmsSendId);
                toast("验证码已发送");

                _pagecode.pushSyn(["产品变更", "办理页面", {"stepNo": "21", "scene": "发送验证码", "businessCode": API_CONFIG.CHANNEL_CODE,"businessName":API_CONFIG.BUSINESS_NAME,"applicationNamen":API_CONFIG.APPLICATION_NAME}]);

                // 请求成功后开始倒计时
                startSmsCountdown();
            } else {
                console.warn('二次短信下发业务失败:', response);
                toast("验证码发送失败: " + (response.data?.message || '未知错误'));
            }
        },
        error: function (xhr, status, error) {
            console.error('二次短信下发请求失败:');
            console.error('状态码:', xhr.status);
            console.error('状态文本:', status);
            console.error('错误信息:', error);
            console.error('响应内容:', xhr.responseText);
            toast("验证码发送失败，请稍后重试");
        }
    });
}


// 2. 二次短信校验接口
function customVerifyTwiceSms(mobile, smsCode, secSmsSendId) {
    // 优先使用传入的secSmsSendId，然后是全局变量，最后是默认值
    const finalSecSmsSendId = secSmsSendId || currentSecSmsSendId || API_CONFIG.DEFAULT_SMS_ID;

    const requestData = {
        mobile: mobile,
        cpid: API_CONFIG.CPID,
        fee: API_CONFIG.FEE,
        channelCode: API_CONFIG.CHANNEL_CODE,
        smsCode: smsCode,
        secSmsSendId: finalSecSmsSendId
    };

    console.log('=== 二次短信校验接口 ===');
    console.log('请求URL:', `${API_CONFIG.BASE_URL}/twiceSmsCheck`);
    console.log('请求参数:', requestData);

    return $.ajax({
        type: 'POST',
        url: `${API_CONFIG.BASE_URL}/twiceSmsCheck`,
        contentType: 'application/json',
        data: JSON.stringify(requestData),
        success: function (response) {
            console.log('二次短信校验响应成功:', response);
        },
        error: function (xhr, status, error) {
            console.error('二次短信校验请求失败:');
            console.error('状态码:', xhr.status);
            console.error('状态文本:', status);
            console.error('错误信息:', error);
            console.error('响应内容:', xhr.responseText);
        }
    });
}


// 3. 产品变更校验接口(二次短信)
function customVerifyProductChange(mobile) {
    const requestData = {
        mobile: mobile,
        cpid: API_CONFIG.CPID,
        fee: API_CONFIG.FEE,
        channelCode: API_CONFIG.CHANNEL_CODE,
        elementTypeCode: "D",
        modifyTag: "0"
    };

    console.log('=== 产品变更校验接口 ===');
    console.log('请求URL:', `${API_CONFIG.BASE_URL}/checkChangeProductTwice`);
    console.log('请求参数:', requestData);

    return $.ajax({
        type: 'POST',
        url: `${API_CONFIG.BASE_URL}/checkChangeProductTwice`,
        contentType: 'application/json',
        data: JSON.stringify(requestData),
        success: function (response) {
            console.log('产品变更校验响应成功:', response);
        },
        error: function (xhr, status, error) {
            console.error('产品变更校验请求失败:');
            console.error('状态码:', xhr.status);
            console.error('状态文本:', status);
            console.error('错误信息:', error);
            console.error('响应内容:', xhr.responseText);
        }
    });
}


// 4. 产品变更办理接口(V2.1.0-二次短信)
function customProcessProductChange(mobile, smsCode) {
    const requestData = {
        mobile: mobile,
        cpid: API_CONFIG.CPID,
        fee: API_CONFIG.FEE,
        channelCode: API_CONFIG.CHANNEL_CODE,
        elementTypeCode: "D",
        modifyTag: "0",
        smsCode: smsCode
    };

    console.log('=== 产品变更办理接口 ===');
    console.log('请求URL:', `${API_CONFIG.BASE_URL}/changeProductUpgradeTwice`);
    console.log('请求参数:', requestData);

    return $.ajax({
        type: 'POST',
        url: `${API_CONFIG.BASE_URL}/changeProductUpgradeTwice`,
        contentType: 'application/json',
        data: JSON.stringify(requestData),
        success: function (response) {
            console.log('产品变更办理响应成功:', response);
        },
        error: function (xhr, status, error) {
            console.error('产品变更办理请求失败:');
            console.error('状态码:', xhr.status);
            console.error('状态文本:', status);
            console.error('错误信息:', error);
            console.error('响应内容:', xhr.responseText);
        }
    });
}


// 5. 客户办理记录接口
function customRecordAdd(mobile, orderNumber, timeRecords) {
    // 获取设备和环境信息
    const userAgent = navigator.userAgent;
    const currentTime = Date.now();

    // 尝试获取设备型号（从userAgent中提取）
    let phoneModelName = 'Unknown';
    const androidMatch = userAgent.match(/Android.*?;\s*(.*?)\s*Build/);
    const iosMatch = userAgent.match(/iPhone.*?OS\s*([\d_]+)/);
    if (androidMatch) {
        phoneModelName = androidMatch[1];
    } else if (iosMatch) {
        phoneModelName = `iPhone iOS ${iosMatch[1].replace(/_/g, '.')}`;
    }

    const requestData = {
        mobile: mobile,
        cpid: API_CONFIG.CPID,
        fee: API_CONFIG.FEE,
        channelCode: API_CONFIG.CHANNEL_CODE,
        orderNumber: orderNumber || 'AUTO_' + currentTime,
        phoneModelName: phoneModelName,
        requestIp: '', // 前端无法直接获取真实IP
        touchSpotUrl: 'https://ldwxmc.com/default/shanxi',
        platformName: document.title || '咪咕尊享包',
        clickUrlTime: timeRecords?.clickUrlTime || currentTime,
        printMobileTime: timeRecords?.printMobileTime || currentTime,
        clickSmsBtnTime: timeRecords?.clickSmsBtnTime || currentTime,
        clickHandleTime: timeRecords?.clickHandleTime || currentTime,
        clikcSecondHandleTime: timeRecords?.clikcSecondHandleTime || currentTime,
        responseSuccessTime: timeRecords?.responseSuccessTime || currentTime,
        getMemberTime: timeRecords?.getMemberTime || currentTime,
        uaInfo: userAgent
    };

    console.log('=== 客户办理记录接口 ===');
    console.log('请求URL:', `${API_CONFIG.BASE_URL}/recordAdd`);
    console.log('请求参数:', requestData);

    return $.ajax({
        type: 'POST',
        url: `${API_CONFIG.BASE_URL}/recordAdd`,
        contentType: 'application/json',
        data: JSON.stringify(requestData),
        success: function (response) {
            console.log('客户办理记录响应成功:', response);
        },
        error: function (xhr, status, error) {
            console.error('客户办理记录请求失败:');
            console.error('状态码:', xhr.status);
            console.error('状态文本:', status);
            console.error('错误信息:', error);
            console.error('响应内容:', xhr.responseText);
        }
    });


    const formattedTime = updateTime();
    // 动态生成显示内容
    $('.orderNumber').text(orderNumber);
    $('.channel').text('成都律动无限');
    $('.phone').text(mobile);
    $('.orderTime').text(formattedTime);
    $('.effectiveTime').text('立即生效');

    $('[st-bind=successConfirm]').removeClass('hide');               
     var option = {
        activityCode: API_CONFIG.CHANNEL_CODE,
        activityCodeId: API_CONFIG.CPID,
        activityName: '陕西移动40元80GB超值流量包',
        channel: '成都律动无限',
        confirmWay: "",
        reconfirmLog: "",
        successfulContent: "业务办理成功",
        accessId:orderNumber,
        tid:'',//进入活动页面调用接口返回的tid值
     };
     CaptureInfor.ScreenCapture('body',option);
    
}

// 6. 插码加密手机号
function encryptMobile(mobile) {


    const requestData = {
        mobile: mobile,
        cpid: API_CONFIG.CPID
    };

    console.log('=== 插码加密手机号 ===');
    console.log('请求URL:', `${API_CONFIG.BASE_URL}/encryptMobile`);
    console.log('请求参数:', requestData);

    return $.ajax({
        type: 'POST',
        url: `${API_CONFIG.BASE_URL}/encryptMobile`,
        contentType: 'application/json',
        data: JSON.stringify(requestData),
        success: function (response) {
            console.log('插码加密手机号:', response);
            if (response.state === 'success') {
                _pagecode.init({user: response.data })
                console.log('获取到插码加密手机号:', response.data);
            } else {
                console.warn('插码加密手机号失败:', response);
                toast("插码加密手机号失败: " + (response.data?.message || '未知错误'));
            }
        },
        error: function (xhr, status, error) {
            console.error('插码加密手机号失败:');
            console.error('状态码:', xhr.status);
            console.error('状态文本:', status);
            console.error('错误信息:', error);
            console.error('响应内容:', xhr.responseText);
            toast("验证码发送失败，请稍后重试");
        }
    });
}
// 初始化全局对象和API
$(document).ready(function () {
    // 全局API对象定义
    window.API = {};

    // Form对象定义
    window.Form = {};

    // 表单数据对象
    window.formData = {
        user: {
            mobile: ""
        },
        form: {
            vcode: ""
        }
    };

    // UI对象定义
    window.ui = {};

    // Form.setPhone方法
    Form.setPhone = function ($input) {
        var phone = $input.val();
        formData.user.mobile = phone;
        // 记录输入手机号时间
        timeRecords.printMobileTime = Date.now();

        // 基本手机号验证
        if (phone.length === 11 && /^1[3-9]\d{9}$/.test(phone)) {
            $input.removeClass('error');
        }
    };

    // API.sms_code方法
    API.sms_code = function () {
        // 验证手机号
        if (!formData.user.mobile || formData.user.mobile.length !== 11) {
            toast('请输入正确的手机号码');
            return;
        }

        // 调用短信发送函数
        customSendTwiceSms(formData.user.mobile);
    };

    // API.handle方法
    API.handle = function () {
        // 验证表单数据
        if (!formData.user.mobile || formData.user.mobile.length !== 11) {
            toast('请输入正确的手机号码');
            return;
        }

        // if (!formData.form.vcode || formData.form.vcode.length !== 6) {
        //     toast('请输入6位验证码');
        //     return;
        // }

        // 调用订购流程
        customExecuteOrderProcess(formData.user.mobile, formData.form.vcode);
    };

    // ui.closeConfirm方法
    ui.closeConfirm = function ($elem) {
        _pagecode.pushSyn(["产品变更", "办理页面", {"stepNo": "-22", "scene": "取消办理", "businessCode": API_CONFIG.CHANNEL_CODE,"businessName":API_CONFIG.BUSINESS_NAME,"applicationNamen":API_CONFIG.APPLICATION_NAME}]);
        $('[st-bind=confirm]').addClass('hide');
    };

    ui.closeSuccessConfirm = function ($elem) {
        $('[st-bind=successConfirm]').addClass('hide');
    };

    // toast提示函数
    window.toast = function (message) {
        // 如果有layui，使用layer.msg
        if (typeof layer !== 'undefined' && layer.msg) {
            layer.msg(message);
        } else {
            // 否则使用alert
            alert(message);
        }
    };

    console.log('API对象初始化完成');
});

// 完整的订购流程 - 第一步：验证码校验
function customExecuteOrderProcess(mobile, smsCode) {
    console.log('executeOrderProcess 被调用了！', { mobile, smsCode, currentSecSmsSendId });

    // 记录点击办理按钮时间
    timeRecords.clickHandleTime = Date.now();

    // 检查是否有有效的secSmsSendId
    if (!currentSecSmsSendId) {
        toast('请先获取验证码');
        return;
    }

    //第1次抓屏
    CaptureInfor.ScreenCapture('body');

    // 步骤1: 二次短信校验
    customVerifyTwiceSms(mobile, smsCode)
        .then(function (response) {
            console.log('二次短信校验结果:', response);
            if (response.data?.returnCode === API_CONFIG.SUCCESS_CODE) {
                // 验证码校验成功，显示确认弹窗
                const formattedTime = updateTime();
                // 更新页面上的时间和日期
                $('#time-container').text(formattedTime);
                $('[st-bind=confirm]').removeClass('hide');

                //第2次抓屏
                CaptureInfor.ScreenCapture('body');
            } else {
                throw new Error('短信验证失败: ' + (response.data?.message || '验证码错误'));
            }
        })
        .catch(function (error) {
            console.error('验证码校验出错:', error);
            toast(error.message || "验证码校验失败，请稍后重试");
        });
}

// 确认订购流程 - 第二步：用户确认后执行订购
function confirmOrderProcess() {

    const mobile = formData.user.mobile;
    const smsCode = formData.form.vcode;

    console.log('confirmOrderProcess 被调用了！', { mobile, smsCode });
    
    _pagecode.pushSyn(["产品变更", "办理页面", {"stepNo": "22", "scene": "确认办理", "businessCode": API_CONFIG.CHANNEL_CODE,"businessName":API_CONFIG.BUSINESS_NAME,"applicationNamen":API_CONFIG.APPLICATION_NAME}]);
    
    // 记录二次确认时间
    timeRecords.clikcSecondHandleTime = Date.now();

    // 隐藏确认弹窗
    $('[st-bind=confirm]').addClass('hide');

    // 步骤2: 产品变更校验
    customVerifyProductChange(mobile)
        .then(function (response) {
            console.log('产品变更校验结果:', response);
            if (response.data?.returnCode === API_CONFIG.SUCCESS_CODE) {
                // 步骤3: 产品变更办理
                return customProcessProductChange(mobile, smsCode);
            } else {
                throw new Error('产品变更校验失败: ' + (response.data?.message || '校验失败'));
            }
        })
        .then(function (response) {
            console.log('产品变更办理结果:', response);
            if (response.data?.returnCode === API_CONFIG.SUCCESS_CODE) {
                // 记录响应成功时间
                timeRecords.responseSuccessTime = Date.now();
                timeRecords.getMemberTime = Date.now();

                toast("订购成功！");
                console.log('订购成功，订单信息:', response.data?.dataInfo);

                // 获取订单号（从返回的dataInfo中获取）
                const orderNumber = response.data?.dataInfo?.orderId || response.data?.dataInfo?.tradeId || 'AUTO_' + Date.now();

                // 调用客户办理记录接口（必须调用，否则下一笔订单无法继续办理）
                console.log('开始调用客户办理记录接口...');
                customRecordAdd(mobile, orderNumber, timeRecords)
                    .then(function (recordResponse) {
                        console.log('客户办理记录成功:', recordResponse);
                    })
                    .catch(function (recordError) {
                        console.error('客户办理记录失败:', recordError);
                        // 记录失败不影响用户体验，但会影响下一笔订单
                    });

                _pagecode.pushSyn(["产品变更", "办理页面", {"stepNo": "99", "scene": "办理成功", "businessCode": API_CONFIG.CHANNEL_CODE,"businessName":API_CONFIG.BUSINESS_NAME,"applicationNamen":API_CONFIG.APPLICATION_NAME}]);  

            } else {
                _pagecode.pushSyn(["产品变更", "办理页面", {"stepNo": "-99", "scene": "办理失败", "businessCode": API_CONFIG.CHANNEL_CODE,"businessName":API_CONFIG.BUSINESS_NAME,"applicationNamen":API_CONFIG.APPLICATION_NAME}]);  
                throw new Error('订购失败: ' + (response.data?.message || '办理失败'));
            }
        })
        .catch(function (error) {
            console.error('订购流程出错:', error);
            toast(error.message || "订购失败，请稍后重试");
        });
}

function updateTime() {
    // 获取当前时间
    const date = new Date();

    // 获取日期部分（格式：2025-05-05）
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需要加 1
    const day = String(date.getDate()).padStart(2, '0');

    // 获取时间部分（格式：10:10:10）
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    return formattedTime;
}
